package org.netty.client;

import com.webside.netty.model.AskMsg;
import com.webside.netty.model.AskParams;
import com.webside.netty.model.Constants;
import com.webside.netty.model.LoginMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.netty.handler.ClientChannelInitializer;

import java.util.concurrent.TimeUnit;

public class NettyClientBootstrap {

    private String host;

    private int port;

    private SocketChannel socketChannel;

    NettyClientBootstrap(String host, int port)
    {
        this.host = host;
        this.port = port;
    }


    public void run() throws InterruptedException {
        EventLoopGroup worker = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker);

        bootstrap.channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ClientChannelInitializer());

        ChannelFuture future =bootstrap.connect(host,port).sync();
        if (future.isSuccess()) {
            socketChannel = (SocketChannel)future.channel();
            System.out.println("connect server  成功---------");
        }
    }



    public static void main(String[] args) {
        Constants.setClientId("001");
        NettyClientBootstrap client = new NettyClientBootstrap("127.0.0.1", 10111);
        LoginMsg loginMsg=new LoginMsg();
        loginMsg.setPassword("wjggwm");
        loginMsg.setUserName("wjggwm");
        client.socketChannel.writeAndFlush(loginMsg);

        while (true){
            try {
                TimeUnit.SECONDS.sleep(3);

            AskMsg askMsg=new AskMsg();
            AskParams askParams=new AskParams();
            askParams.setAuth("authToken");
            askMsg.setParams(askParams);
            client.socketChannel.writeAndFlush(askMsg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
